﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.Components;
using Aliyeye.Car.Net.UI.PopupDialog;
using Aliyeye.Car.Net.UI.Common;
using Aliyeye.Car.Net.UI.PrintExport;
using Aliyeye.Car.Net.UI.Controls;


namespace Aliyeye.Car.Net.UI.OrderModel
{
    /// <summary>
    /// 短租自驾
    /// </summary>
    public partial class ShortLeaseWithOutDriverList : Aliyeye.Car.Net.UI.BaseForm
    {
        private string strWhere = string.Empty;
        private bool isShortLease = false;
        ArchivesSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.ArchivesSvc.SoapHeaderClass();

        public ShortLeaseWithOutDriverList()
        {
            InitializeComponent();
        }

        public ShortLeaseWithOutDriverList(bool isShortLe)
        {
            InitializeComponent();
            isShortLease = isShortLe;

            if (!isShortLease)
            {
                this.Text = "长租自驾预定";
                this.toolStripLabel1.Text = "长租自驾预定";
            }
        }

        private void ShortLeaseWithDriverList_Load(object sender, EventArgs e)
        {
            BindComboBoxInfo();
            this.pager1.PageCurrent = 1;
            this.pager1.Bind();
        }

        private void BindComboBoxInfo()
        {
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            string strWhere = string.Empty;
            DataSet dt = null;

            ServiceManipulator.SafeAsyncExecution<ArchivesSvc.ArchivesServiceSoapClient>(
                proxy => proxy.ComBoxBrand(sopaHeader),
                result =>
                {
                    if (result.Error == null)
                    {
                        dt = (DataSet)result.Result;

                        DataRow dr = dt.Tables[0].NewRow();
                        dr["Id"] = "-1";
                        dr["Name"] = "全部";
                        dr["Namevalue"] = "全部";
                        dt.Tables[0].Rows.Add(dr);

                        DataView dv = dt.Tables[0].DefaultView;
                        dv.Sort = "id asc";

                        CmbCusCartype.DisplayMember = "Namevalue";
                        CmbCusCartype.ValueMember = "Id";
                        CmbCusCartype.DataSource = dv;
                        CmbCusCartype.SelectedIndex = 0;

                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private int dgvBind()
        {
            string _strSql = "Drive='false' and IsActive='true' ";
            string _strSql2 = "";
            //if (isShortLease)
            //    _strSql2 += " and (Reserve.Type!='1' or Reserve.Type is null) ";   // 如果是短租自驾，则不搜索长租自驾的并且已经订车的车辆信息
            //else
            //    _strSql2 += " and (Reserve.Type!='2' or Reserve.Type is null) ";

            string strSearch = strWhere;
            PageData pageData = new PageData(this, pager1, this.overlay);

            pageData.TableName = "  Car";
            pageData.PrimaryKey = "Car.Id";
            pageData.OrderStr = "Car.Id desc";
            pageData.PageIndex = this.pager1.PageCurrent;
            pageData.PageSize = this.pager1.PageSize;
            pageData.QueryCondition = _strSql + _strSql2 + strSearch.ToString();
            pageData.QueryFieldName = "IsSelf,Code,State,DayRent,Brand,Cartype,Car.Seat,ExhaustVolume,Max,WarrTime,InsureEnd,BuyTime,Color,OvertimePrie,DayLimitKM,TimeoutPrie,Id,MonthRent,YearRent,MonthDeposit,YearDeposit,(select Count(*) from Reserve where BookTime<=getdate() and EndBooktime>=getdate() and OrderSataus='false' and Reserve.CarId=Car.id) as orderNumber";

            dgvInfo.AutoGenerateColumns = false;
            DataSet ds = pageData.QueryDataTable();
            dgvInfo.DataSource = this.pager1.bindingSource;
            return pageData.TotalCount;
        }

        private void ExportAllSearchCondistion()
        {
            string _strSql = "Drive='false' and IsActive='true' ";
            string _strSql2 = "";
            //if (isShortLease)
            //    _strSql2 += " and (Reserve.Type!='1' or Reserve.Type is null)";   // 如果是短租自驾，则不搜索长租自驾的并且已经订车的车辆信息
            //else
            //    _strSql2 += " and (Reserve.Type!='2' or Reserve.Type is null)";
            //string strWhere = strSearch;
            string strOrderBy = " order by Car.Id desc";
            string strSelect = "select IsSelf,Code,State,DayRent,Brand,Cartype,Car.Seat,ExhaustVolume,Max,WarrTime,InsureEnd,BuyTime,Color,OvertimePrie,DayLimitKM,TimeoutPrie,Id,MonthRent,YearRent,MonthDeposit,YearDeposit,MotorCode,dipanCode,CareTime,StarCheshui,(select Count(*) from Reserve where BookTime<=getdate() and EndBooktime>=getdate() and OrderSataus='false' and Reserve.CarId=Car.id) as orderNumber  from Car";
            string strSql = strSelect + " where " + _strSql + _strSql2 + strWhere.ToString() + strOrderBy;

            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            CarSvc.SoapHeaderClass sopaHeader = new CarSvc.SoapHeaderClass();

            DataSet dsCars = null;
            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                proxy => proxy.GetAllListForSearchCondistion(sopaHeader, strSql),
                result =>
                {
                    if (result.Error == null)
                    {
                        dsCars = (DataSet)result.Result;
                        //开始导出
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            string filePath = saveFileDialog.FileName;
                            ExcelHelper excelHelper = new ExcelHelper();
                            string msg = "";
                            if (excelHelper.OrderWithOutDriverListExport(dsCars, filePath, ref msg))
                            {
                                PageCommon.Notify("文档导出成功！");
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                            else
                            {
                                PageCommon.Alert(msg);
                                overlay.FadeOut(); Cursor.Current = Cursors.Default;
                            }
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message);
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private int pager1_EventPaging(EventPagingArg e)
        {
            return dgvBind();
        }

        private void dgvInfo_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (IsANonHeaderButtonCell(e))
            {
                ButtonClicked(e);
            }
        }

        private void ButtonClicked(DataGridViewCellEventArgs e)
        {
            String strButtonContent = dgvInfo.Columns[e.ColumnIndex].Name;
            String id = dgvInfo.Rows[e.RowIndex].Cells["ID"].Value.ToString();
            String MonthRent = dgvInfo.Rows[e.RowIndex].Cells["每月租金"].Value.ToString();
            String YearRent = dgvInfo.Rows[e.RowIndex].Cells["每年租金"].Value.ToString();
            String MonthDeposit = dgvInfo.Rows[e.RowIndex].Cells["每月押金"].Value.ToString();
            String YearDeposit = dgvInfo.Rows[e.RowIndex].Cells["每年押金"].Value.ToString();

            int reserveId = 0;
            if (dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value != null && dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value.ToString().Trim() != "")
                reserveId = Convert.ToInt32(dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value.ToString());
            if (strButtonContent.Trim().Equals("查看订购"))
            {
                ReserveSvc.SoapHeaderClass sopaHeaderReserveSvc2 = new Aliyeye.Car.Net.UI.ReserveSvc.SoapHeaderClass();
                ReserveSvc.ReserveServiceSoapClient client = new Aliyeye.Car.Net.UI.ReserveSvc.ReserveServiceSoapClient();
                DataSet ds = client.GetList(sopaHeaderReserveSvc2, "");
                if (ds != null)
                {
                    if (ds.Tables[0].Rows.Count >= 100)
                    {
                        PageCommon.Alert("数据库空间不足 ，请联络QQ：539217021续费！");
                        return;
                    }
                }

                ReserveShortWithOutDriver userForm = new ReserveShortWithOutDriver(isShortLease, Convert.ToInt32(id), reserveId, MonthRent, YearRent, MonthDeposit, YearDeposit);
                userForm.ShowDialog();
            }
            if (strButtonContent.Trim().Equals("还车"))
            {
                if (reserveId <= 0)
                {
                    PageCommon.Alert("此车没有订车！请重新操作！");
                    return;
                }

                if (PageCommon.Confirm("确定要还车吗？"))
                {

                    Settlement show = new Settlement(Convert.ToInt32(id), reserveId);
                    show.ShowDialog();
                }
            }
            //补款续租
            if (strButtonContent.Trim().Equals("补款续租"))
            {
                if (reserveId <= 0)
                {
                    PageCommon.Alert("此车没有订车！请重新操作！");
                    return;
                }
                MakeMoneyRenewal show = new MakeMoneyRenewal(reserveId);
                show.ShowDialog();
            }
            this.pager1.Bind();
        }

        private bool IsANonHeaderButtonCell(DataGridViewCellEventArgs cellEvent)
        {
            if (dgvInfo.Columns[cellEvent.ColumnIndex] is
                 DataGridViewButtonColumn &&
                 cellEvent.RowIndex != -1)
            { return true; }
            else { return (false); }
        }

        //搜索
        private void btnSearch_Click(object sender, EventArgs e)
        {
            strWhere = "";
            if (CmbCusCartype.Text.Trim() != "全部")
            {
                strWhere += "And Brand= '" + CmbCusCartype.Text.Trim() + "'";
            }
            if (!string.IsNullOrEmpty(txtCarCode.Text))
            {
                strWhere += " And Car.Code like '%" + txtCarCode.Text + "%'";
            }

            if (!string.IsNullOrEmpty(txtDayRentjs.Text))
            {
                strWhere += " And DayRent<=" + decimal.Parse(txtDayRentjs.Text);
            }

            if (!string.IsNullOrEmpty(txtDayRentks.Text))
            {
                strWhere += " And DayRent>=" + decimal.Parse(txtDayRentks.Text);
            }



            this.pager1.Bind();
        }

        //全部
        private void btnAll_Click(object sender, EventArgs e)
        {
            txtDayRentjs.Text = "";
            txtDayRentks.Text = "";
            txtCarCode.Text = "";
            strWhere = "";
            this.pager1.Bind();
        }

        private void dgvInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvInfo.Rows.Count; )
                {
                    this.dgvInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "状态")
            {
                if (e.Value != null)
                {
                    if (Convert.ToInt32(e.Value) > 0)
                    {
                        e.Value = "租用中";
                        this.dgvInfo.Rows[e.RowIndex].DefaultCellStyle.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        e.Value = "待租中";
                        e.CellStyle.ForeColor = Color.Blue;
                    }
                }
            }
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "还车日")
            {
                if (e.Value != null)
                {
                    string strCarTime = "";
                    strCarTime = Convert.ToDateTime(e.Value.ToString().Trim()).ToString("yyyy-MM-dd");
                    if (strCarTime == "1990-01-01")
                        e.Value = "";
                }
            }
            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "属性")
            {
                if (e.Value != null)
                {
                    if (Convert.ToBoolean(e.Value))
                    {
                        e.Value = "自";
                    }
                    else
                    {
                        e.Value = "靠";
                        e.CellStyle.ForeColor = Color.Red;
                    }
                }
            }

            if (this.dgvInfo.Columns[e.ColumnIndex].Name == "每日租金")
            {
                if (e.Value != null)
                {
                    if (!isShortLease)
                    {
                        string MonthRent = this.dgvInfo.Rows[e.RowIndex].Cells["每月租金"].Value.ToString();
                        string YearRent = this.dgvInfo.Rows[e.RowIndex].Cells["每年租金"].Value.ToString();
                        MonthRent = MonthRent.Trim() == "" ? "0" : MonthRent;
                        YearRent = YearRent.Trim() == "" ? "0" : YearRent;
                        e.Value = MonthRent + " / " + YearRent;
                        this.dgvInfo.Columns[e.ColumnIndex].HeaderText = "每月租金 / 每年租金";
                        this.dgvInfo.Columns[e.ColumnIndex].Width = 170;
                    }
                }
            }
            //if (this.dgvInfo.Columns[e.ColumnIndex].Name == "还车")
            //{
            //    if (dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value == null || dgvInfo.Rows[e.RowIndex].Cells["ReserveId"].Value.ToString().Trim() == "")
            //    {
            //        //DataGridViewDisableButtonCell buttonCell = (DataGridViewDisableButtonCell)dgvInfo.Rows[e.RowIndex].Cells["还车"];
            //        //buttonCell.Enabled = false;

            //    }
            //}
        }

        private void txtDayRentks_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsNumberMoney(txtDayRentks, e);
        }

        private void txtDayRentjs_KeyPress(object sender, KeyPressEventArgs e)
        {
            IsNumberMoney(txtDayRentjs, e);
        }
        private bool IsNumberMoney(System.Windows.Forms.TextBox t, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '.' || e.KeyChar == 8 || e.KeyChar == 13))
            {
                return true;
            }
            else
            {
                DialogNotify diaSecc = new DialogNotify("只能输入数字！");
                diaSecc.ShowDialog();
                e.Handled = true;
                return false;
            }
        }

        //导出
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportAllSearchCondistion();
        }

        #region 车牌号 输入框数据绑定

        string driverName = string.Empty;
        private void txtCarCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                string strSearch = this.txtCarCode.Text;
                if (string.IsNullOrEmpty(strSearch))
                {
                    DialogWarning dia = new DialogWarning("车牌号不能为空！");
                    dia.ShowDialog();
                    return;
                }
                else
                {
                    DisplayCarLIst(strSearch, "车牌号");
                }
            }
        }

        private void DisplayCarLIst(string strSearch, string type)
        {
            if (string.IsNullOrEmpty(strSearch))
            {
                return;
            }
            string strSelectWhere = "";
            if (type == "车牌号")
            {
                strSelectWhere = " Code like '%" + strSearch + "%'";
            }
            overlay.FadeIn(); Cursor.Current = Cursors.WaitCursor;
            DataSet ds = null;
            this.dgvDriverInfo.DataSource = null;
            dgvDriverInfo.AutoGenerateColumns = false;
            CarSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.CarSvc.SoapHeaderClass();
            ServiceManipulator.SafeAsyncExecution<CarSvc.CarServiceSoapClient>(
                proxy => proxy.GetList(sopaHeader, strSelectWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;
                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            dgvDriverInfo.DataSource = ds.Tables[0];
                            this.dgvDriverInfo.Visible = true;
                            this.dgvDriverInfo.Focus();
                        }
                        else
                        {
                            PageCommon.Alert("查找的车辆不存在，请重新查询！");
                            txtCarCode.Text = driverName;
                        }
                        overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut(); Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        private void dgvDriveInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (this.dgvDriverInfo.Rows.Count != 0)
            {
                for (int i = 0; i < this.dgvDriverInfo.Rows.Count; )
                {
                    this.dgvDriverInfo.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.PapayaWhip;
                    i += 2;
                }
            }
        }

        private void dgvDriverInfo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Return)
            {
                this.txtCarCode.Text = this.dgvDriverInfo.CurrentRow.Cells["车牌号1"].Value.ToString();
                //  driverID = Convert.ToInt32(this.dgvInfo.CurrentRow.Cells["编号"].Value.ToString());
                driverName = this.txtCarCode.Text;
                this.dgvDriverInfo.Visible = false;
                this.txtDayRentks.Focus();
            }
        }

        private void dgvDriverInfo_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            e.CellStyle.WrapMode = DataGridViewTriState.True;
            if (this.dgvDriverInfo.Columns[e.ColumnIndex].Name == "性别")
            {
                if (e.Value != null)
                {
                    if (Convert.ToBoolean(e.Value))
                    {
                        e.Value = "带驾";
                    }
                    else
                    {
                        e.Value = "自驾";
                    }
                }
            }
        }

        #endregion 车牌号 输入框数据绑定

    }
}
